<template>
  <div>
    <ListTab
      v-model="activeId"
      :show-header="!showMobilePage"
      :padding-left="isDustbin?'32px':'16px'"
      :tabs="tabListData"
      :mode="orderMode"
      :mode-list="modeList"
      is-table
      @tabClick="handleTabClick"/>
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="order min-fill-page">
      <dataDisplay
        v-if="!isDustbin"
        :data-list="displayData"
        class="mobile-data"
        style="margin-bottom:16px;"
      />
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          :is-show-filter="isShowFilter"
          show-search-btn
          is-search-resource
          is-show-config
          @selectChange="handelFilterInputChange"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus">
          <template slot="valueAppend" slot-scope="scope">
            <el-checkbox
              v-if="scope.keyword === 'clientName'"
              v-model="paramsObj.exactForClientName"
              :true-label="1"
              :false-label="0"
              style="position: relative;">精准搜索</el-checkbox>
            <el-checkbox
              v-if="scope.keyword === 'actualClientName'"
              v-model="paramsObj.exactForActualClientName"
              :true-label="1"
              :false-label="0"
              style="position: relative;">精准搜索</el-checkbox>
          </template>
        </FilterInput>
        <div class="table-top-opeator-bar">
          <template v-if="!isDustbin">
            <el-popover v-model="popoverVisible" :width="260" popper-class="view-filter-popover" @hide="cancelEdit">
              <ul class="view-box">
                <li v-for="item in viewOptions" :key="item.id" :class="{ 'active-view': curView === item.id && !item.edit, 'pl0': item.edit }" class="view-option" @click="changeView(item)">
                  <el-input v-if="item.edit" v-model="editMode.name" :maxlength="64" size="small" class="tag-input mr4" placeholder="请输入视图名称" @click.stop.native="() => {}"/>
                  <ToolTip v-else :content="item.name" style="width: calc(100% - 60px)" />
                  <div v-if="item.id !== -1" class="flex">
                    <img :src="EditIcon" class="operate-icon" @click.stop="handleEditView(item)">
                    <img :src="DeleteIcon" class="operate-icon" style="margin: 0 4px 0 10px" @click.stop="handleDelView(item.id)">
                  </div>
                </li>
                <div v-if="inEdit" class="operate-btn">
                  <el-button class="edit-btn mobile-btn-flex" type="primary" size="small" @click="handleSaveEdit">
                    保存
                  </el-button>
                  <el-button class="back-btn cancel-btn-style" type="info" size="small" @click="cancelEdit">
                    取消
                  </el-button>
                </div>
              </ul>
              <div slot="reference" class="default-view flex-center">
                <div class="view-name flex-center">
                  <ToolTip :content="getCurView()" />
                </div>
                <div class="view-icon flxe-center">
                  <img :src="editViewIcon" width="16" height="16" alt="" @click.stop="openSetting">
                </div>
              </div>
            </el-popover>
            <createBtn v-if="hasRouteAuth('crm:orderList:add') || hasRouteAuth('crm:orderList:addDraft')" style="margin-right:10px;" @click.native="createOrder" />
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="[
                {label: '自定义列', handelClick: openSetting},
                {label: '批量新增', handelClick: toCreate, auth: hasRouteAuth('crm:orderList:add') || hasRouteAuth('crm:orderList:addDraft')},
                {label: '批量开启采集', handelClick: batchPick, auth: hasRouteAuth('crm:orderList:batchPick') && orderMode === 0},
                {label: '关联询单', handelClick: relatedQueryOrder, divided: true},
                {label: '批量发布', handelClick: batchPublish, auth: activeName === '待发布' && hasRouteAuth('crm:orderList:publish')},
                {label: '批量审批', handelClick: batchExamine, auth: activeName === '待审批' && hasRouteAuth('crm:orderList:examine')},
                {label: '批量撤回', handelClick: batchBack, auth: activeName === '待核算'|| activeName === '待审批' || activeName === '待封账'},
                {label: '财务报表导出', handelClick: openDateDialog, auth: hasRouteAuth('crm:orderList:exportFinance'), divided: true},
                {label: '按变更模板导出', exportApi: '/admin/order/export', auth: hasRouteAuth('crm:orderList:export') && orderMode === 0, type: 'export', exportName: '订单明细', isBeforeExport: true, beforeExport: exportTemplateExport, refName: 'templateExportRef', tip: '按变更模板导出订单,导出并修改值后即可直接导入' },
                {label: '导出', type: 'export', auth: hasRouteAuth('crm:orderList:export'), exportApi:'/admin/order/export', exportName:'订单明细', isBeforeExport: true, beforeExport: exportBeforeExport, refName: 'exportRef'},
                {label: '导入', handelClick: uploadDialogShow, auth: hasImportAuth, divided: hasImportAuth }
              ]"
              style="margin-right:10px;"
            />
          </template>
          <div v-else-if="hasRouteAuth('crm:orderList:delete')">
            <el-button v-if="hasRouteAuth('crm:orderList:dustbinBatchDelete')" style="margin-left:12px;height:32px;padding: 7px 11px;" size="small" @click="toDeleteDialog(null)">批量删除</el-button>
            <el-button v-if="hasRouteAuth('crm:orderList:dustbinBatchRestore')" style="margin-left:12px;height:32px;padding: 7px 11px;" type="primary" size="small" @click="toRecoveryDialog(null)">批量还原</el-button>
          </div>
        </div>
      </div>
      <div class="table-list">
        <div v-loading="listLoading" v-if="list.isInit" style="height: 300px" />
        <orderTable
          v-else
          ref="orderTableContainer"
          :examine-loading="examineLoading"
          :is-dustbin="isDustbin"
          :list="list"
          :list-loading="listLoading"
          :order-list-setting="orderListSetting"
          :active-id="activeId"
          :table-height="setTableHeight"
          @sortMethod="sortMethod"
          @fetchData="fetchData"
          @torecoverydialog="toRecoveryDialog"
          @toDeleteDialog="toDeleteDialog"
          @examine="batchExamine"
          @btnDel="btnDel"
          @handleSelectionChange="handleSelectionChange" />
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="selectOrderList" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-row>
        <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              :is-show-filter="isShowFilter"
              show-search-btn
              show-mobile-icon
              is-search-resource
              @selectChange="handelFilterInputChange"
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus">
              <template slot="valueAppend" slot-scope="scope">
                <el-checkbox
                  v-if="scope.keyword === 'clientName'"
                  v-model="paramsObj.exactForClientName"
                  :true-label="1"
                  :false-label="0"
                  style="position: relative; top: 4px;">精准搜索</el-checkbox>
                <el-checkbox
                  v-if="scope.keyword === 'actualClientName'"
                  v-model="paramsObj.exactForActualClientName"
                  :true-label="1"
                  :false-label="0"
                  style="position: relative; top: 4px;">精准搜索</el-checkbox>
              </template>
            </FilterInput>
            <MoreOpeator
              v-if="!isDustbin"
              ref="moreOpeatorRef"
              :list="[
                {label: '自定义列', handelClick: openSetting},
                {label: '关联询单', handelClick: relatedQueryOrder, divided: true},
                {label: '批量新增', handelClick: toCreate, auth: hasRouteAuth('crm:orderList:add') || hasRouteAuth('crm:orderList:addDraft')},
                {label: '批量发布', handelClick: batchPublish, auth: activeName === '待发布' && hasRouteAuth('crm:orderList:publish')},
                {label: '批量审批', handelClick: batchExamine, auth: activeName === '待审批' && hasRouteAuth('crm:orderList:examine')},
                {label: '批量撤回', handelClick: batchBack, auth: activeName === '待发布' || activeName === '待核算'|| activeName === '待审批' || activeName === '待封账'},
                {label: '批量删除', handelClick: tobatchDelOrder, auth: hasRouteAuth('crm:orderList:delete') && activeId < 4},
                {label: '批量开启采集', handelClick: batchPick, auth: hasRouteAuth('crm:orderList:batchPick') && orderMode === 0},
                {label: '更新账号信息', handelClick: tobatchUpdate, auth: canUpdateAccount},
                {label: '财务报表导出', handelClick: openDateDialog, auth: hasRouteAuth('crm:orderList:exportFinance'), divided: true},
                {label: '按变更模板导出', exportApi: '/admin/order/export', auth: hasRouteAuth('crm:orderList:export') && orderMode === 0, type: 'export', exportName: '订单明细', isBeforeExport: true, beforeExport: exportTemplateExport, refName: 'templateExportRef', tip: '按变更模板导出订单,导出并修改值后即可直接导入' },
                // {label: '一键开票', handelClick: tobatchCreateInvoice, auth: activeId < 6}, // v3.3.8隐藏一键开票入口
                {label:'导出', type: 'export', auth: hasRouteAuth('crm:orderList:export'), exportApi:'/admin/order/export', exportName:'订单明细', isBeforeExport: true, beforeExport: exportBeforeExport, refName: 'exportRef'},
                {label:'导入', handelClick:uploadDialogShow, auth: hasImportAuth, divided: true }
              ]"
              label="批量操作"
              show-mobile-icon
            />
            <createBtn v-if="hasRouteAuth('invoice:issue:create')" mobile-table @click.native="createOrder"/>
          </template>
          <template v-else>
            <div class="delete-button-container">
              <MoreOpeator
                v-if="!isDustbin"
                :list="[
                  {label: '批量删除', handelClick: tobatchDelOrder, auth: hasRouteAuth('crm:orderList:delete') && activeId < 4},
                  // {label: '一键开票', handelClick: tobatchCreateInvoice, auth: activeId < 6},
                  {label: '更新账号信息', handelClick: tobatchUpdate, auth: canUpdateAccount},
                  {label: '批量开启采集', handelClick: batchPick, auth: hasRouteAuth('crm:orderList:batchPick') && orderMode === 0}
                ]"
                label="批量操作"
                style="margin-right:14px;"
              />
              <SelectionNum :select-item="selectOrderList" @clearMixinSelection="clearMixinSelection" />
            </div>
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes,jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
      <Examine ref="examineRef" @setLoading="setExamineLoading" @fetchData="fetchData" @clearMixinSelection="clearMixinSelection" />
      <updateInfoDialog ref="updateInfoDialog" @clearSelectionFun="clearMixinSelection" @updateList="updateList" />
      <orderSetting ref="orderSetting" :setting-type="'order'" :init-order-list="initOrderList" @handelSubmit="handelSubmit" @freshViewList="getViewList"/>
    </div>
    <relatedQueryOrder
      ref="showRelatedQueryOrder"
      :visible.sync="showRelatedQueryOrder"
      @confirmRelatedQueryOrder="confirmRelatedQueryOrder"
    />
    <financeDialog
      ref="exportFinance"
      :date-dialog="dateDialog"
      :need-category-ary="needCategoryAry"
      @closeDialog="closeDateDialog"
    />
    <UploadDialog
      ref="uploadDialogRef"
      @uploadList="fetchData"
    />
  </div>
</template>

<script>
// mixin
import SelectOption from './mixins/selectOption';
import recoveryMixin from './mixins/recovery';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
// api
import { getList, delOrder, getOrderStatistics, getOrderSetting, batchDelOrder, publishOrder, batchPick,
  queryOrderRelated, getOrderView, delOrderView, editOrderView } from '@/api/order';
import { getOrderListTab, getIncomeType, platformList, getNeedCategoryList, orderFormList } from '@/api/select';
import { costList, getDepartmentAll, getTagAll } from '@/api/config';
import { getOperateoptions } from '@/api/resource';
// components
import orderSetting from '@/components/OrderList/orderSetting';
import orderTable from '@/components/OrderList/orderTable';
import Examine from '@/components/OrderList/examine';
import ListTab from '@/components/ListTab';
import FilterInput from '@/components/Tool/filter';
import axios from 'axios';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import { initOrderList } from '@/components/OrderList/settingData';
import updateInfoDialog from '@/components/CreateOrder/updateInfo';
import financeDialog from './model/financeDialog';
import UploadDialog from './model/uploadDialog';
import relatedQueryOrder from '@/components/RelatedQueryOrder/relatedQueryOrder.vue';
// img
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import maoriIcon from '@/assets/chargeOffDetail/maori.png';
import costIcon from '@/assets/dataDisplay/icon_45.png';
import rmb from '@/assets/dataDisplay/rmb.png';
import EditIcon from '@/assets/config/editIcon.png';
import DeleteIcon from '@/assets/config/deleteIcon.png';
import del from '@/assets/setting/del.png';
import delActive from '@/assets/setting/del-active.png';
import editViewIcon from '@/assets/edit-active.png';
// filter
import { hasRouteAuth } from '@/utils/permission';
import ElMessage, { showModal } from '@/utils/message';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
// 下拉选项数据
import {
  orderOption, costWriteOption, costConfirmOption,
  sealBillOption, reviewStateOption, resourceOption,
  settlementStatusOption, costSettlementStatusOption
} from './model/selectData';
import { verificationOptions } from '@/views/project/model/selectData';
import { TAG_MODULES } from '@/utils/const';
import { strJsonParse } from '@/utils/index';

export default {
  name: 'Order',
  components: {
    FilterInput,
    createBtn,
    orderSetting,
    orderTable,
    updateInfoDialog,
    financeDialog,
    UploadDialog,
    relatedQueryOrder,
    ListTab, Examine, dataDisplay, MoreOpeator, btnGroup
  },
  mixins: [SelectOption, recoveryMixin, TableAdaptive, mobileTable],
  data() {
    return {
      costIcon,
      maoriIcon,
      editViewIcon,
      incomeAmountIcon,
      EditIcon,
      DeleteIcon,
      del,
      delActive,
      TAG_MODULES,
      initOrderList,
      paramsObj: {},
      orderMode: 0,
      orderStatus: '',
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      page: 1,
      listLoading: true,
      // showUploadDialog: false,
      examineLoading: false,
      orderStatistics: {},
      orderListSetting: [],
      tabList: [],
      activeId: '',
      cancelToken: null,
      selectOrderList: [],
      incomeOptions: [],
      costItemOptions: [],
      operateModeList: [], // 运营模式列表
      mediumBtnStyle: {
        width: '100px',
        display: 'flex',
        justifyContent: 'center'
      },
      sortName: '',
      sortType: '',
      editMode: {
        id: -1,
        name: ''
      },
      isShowFilter: false,
      orderPlatformOption: [],
      orderFormOption: [],
      needCategoryAry: [],
      deptTreeList: [],
      tagTreeList: [],
      dateDialog: false,
      showRelatedQueryOrder: false,
      supplierType: [{ label: '公司', value: 0 }, { label: '个人', value: 1 }],
      rangeKeyArr: [
        { attr: 'orderTime', start: 'orderStartTime', end: 'orderEndTime', type: 'time' },
        { attr: 'orderSealMonth', start: 'orderSealMonthStart', end: 'orderSealMonthEnd', type: 'time' },
        { attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time' },
        { attr: 'arrivalTime', start: 'arrivalStartTime', end: 'arrivaltEndTime', type: 'time' },
        { attr: 'deleteTime', start: 'deleteStartTime', end: 'deleteEndTime', type: 'time' },
        { attr: 'costTime', start: 'costStartTime', end: 'costEndTime', type: 'time' },
        { attr: 'taxAmount', start: 'taxAmountStart', end: 'taxAmountEnd', type: 'moneyFixed' }
      ],
      arrayKeyArr: ['tag', 'operateMode', 'resourceAttributionMatrixId', 'orderPlatformId', 'costItem', 'departmentId', 'cooperationDepartment', 'accountState'],
      scrollLeft: 0,
      viewOptions: [{ id: -1, name: '默认视图', edit: false }],
      curView: -1,
      curViewName: '默认视图',
      visible: false,
      input: '',
      defaultListSetting: [],
      editView: false,
      popoverVisible: false
    };
  },
  computed: {
    /**
      - 客户信息查看/编辑：勾选状态下，可 查看/编辑 订单用户信息(含列表、详情)
      - 发布信息编辑：勾选状态下，可 编辑 下单链接/上传文件信息：
      - 成本信息编辑：勾选状态下，可 编辑 除微任务成本/ID外的成本信息
      - 其他信息编辑：勾选状态下，可 编辑 除客户、发布、成本外的信息
    */
    isClientInfo() {
      return hasRouteAuth('crm:orderList:clientInfo');
    },
    // 前面三个权限只要有一个没勾选，则无法新增和导入订单
    /* hasCreateOrder() {
      const isPublishInfo = hasRouteAuth('crm:orderList:publishInfo');
      const isOtherInfo = hasRouteAuth('crm:orderList:otherInfo');
      return this.isClientInfo && isPublishInfo && isOtherInfo;
    }, */
    activeName() {
      const item = this.tabList.find(i => i.id === this.activeId);
      return item ? item.name : '全部';
    },
    canUpdateAccount() {
      return this.orderMode === 1 ? this.hasRouteAuth('crm:orderList:finalUpdate') : this.hasRouteAuth('crm:orderList:update');
    },
    isDustbin() {
      return this.activeId === -2;
    },
    hasImportAuth() {
      return hasRouteAuth(['crm:orderList:import', 'crm:orderList:batchUpload', 'crm:orderList:allCostImport', 'crm:orderList:microCostImport']);
    },
    tableOutsideHeight() {
      if (this.showMobilePage) {
        return this.isDustbin ? 203 : 261;
      }
      return this.activeId === -2 ? 188 : 246;
    },
    filterList() {
      const activeName = this.activeName;
      /**
       * disabled：为true时该条筛选不会出现在页面上，有的筛选项在某些条件下不显示，可以通过这个条件处理
       */
      const arr = [
        // 输入框
        { keyword: 'orderId', labelWidth: '96px', name: '订单编号', type: 'input' },
        { keyword: 'queryOrderSn', labelWidth: '96px', name: '关联询单', type: 'input' },
        { keyword: 'clientName', labelWidth: '96px', name: '客户名称', type: 'input', placeholder: '支持分号搜索多个', showAppend: true, disabled: !this.isClientInfo },
        { keyword: 'actualClientName', labelWidth: '96px', name: '实际客户名称', type: 'input', placeholder: '支持分号搜索多个', showAppend: true, disabled: !this.isClientInfo },
        { keyword: 'resourceName', labelWidth: '96px', name: '账号', type: 'input' },
        { keyword: 'orderOperator', labelWidth: '96px', name: '执行人', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'orderBusinessOperator', labelWidth: '96px', name: '执行人(商务侧)', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'orderResourceOperator', labelWidth: '96px', name: '执行人(资源侧)', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'accounts', name: '批量搜索账号', labelWidth: '96px', type: 'input',
          inputType: 'textarea', lengthLimit: false, placeholder: '可通过粘贴快速填写账号名称，每行代表一个账号名称' },
        { keyword: 'creator', labelWidth: '96px', name: '创建人', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        // { keyword: 'attributionMatrix', name: '所属部门', type: 'input' },
        { keyword: 'market', labelWidth: '96px', name: '销售', type: 'conditionInput', doubleClick: true, placeholder: '请输入，双击填充当前用户', excludeKey: 'marketEqual' },
        { keyword: 'supplier', labelWidth: '96px', name: '供应商', type: 'input' },
        // { keyword: 'orderKindName', name: '订单分类', type: 'input' }, <!-- v2.9.6 隐藏订单分类 -->
        { keyword: 'contactPerson', labelWidth: '96px', name: '客户联系人', type: 'input', disabled: !this.isClientInfo },
        { keyword: 'performanceMonth', labelWidth: '96px', name: '业绩月份', type: 'input' },
        { keyword: 'theme', labelWidth: '96px', name: '品牌名称', type: 'input' },
        { keyword: 'remark', labelWidth: '96px', name: '备注', type: 'input' },
        { keyword: 'resourceCode', labelWidth: '96px', name: '账号ID', type: 'input' },
        { keyword: 'systemId', labelWidth: '96px', name: '系统ID', type: 'input' },
        { keyword: 'cooperation', labelWidth: '96px', name: '合作运营方', type: 'input' },
        { keyword: 'accountOperationList', labelWidth: '96px', name: '所有人员', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'customerOrderNum', labelWidth: '96px', name: '客户订单编号', type: 'input', disabled: !this.isClientInfo },
        { keyword: 'taxAmount', labelWidth: '96px', name: '含税金额', type: 'inputRange' },
        // 下拉
        { keyword: 'orderPlatformId', name: '下单平台', type: 'mulSelect', options: this.orderPlatformOption },
        { keyword: 'orderFormId', name: '下单形式', type: 'select', emptyText: '请先选择下单平台', options: this.orderFormOption },
        { keyword: 'settleStatus', name: '客户结算', type: 'select', options: settlementStatusOption },
        { keyword: 'costSettleStatus', name: '成本结算', type: 'select', options: costSettlementStatusOption },
        { keyword: 'costItem', name: '成本项', type: 'mulSelect', options: this.costItemOptions },
        { keyword: 'incomeType', name: '收入类型', type: 'select', options: this.incomeOptions },
        { keyword: 'needCategoryId', name: '品牌标签', type: 'cascaderSelect', options: this.needCategoryAry },
        { keyword: 'orderType', name: '订单类型', type: 'select', options: orderOption, disabled: this.orderMode === 1 },
        { keyword: 'resourceType', name: '资源类型', type: 'select', options: resourceOption },
        { keyword: 'supplierType', name: '供应商类型', type: 'select', options: this.supplierType },
        { keyword: 'accountState', name: '核销状态', type: 'mulSelect', options: verificationOptions, disabled: activeName === '待核销' },
        { keyword: 'sealBillType', name: '封账状态', type: 'select', options: sealBillOption, disabled: activeName === '待封账' },
        { keyword: 'reviewStateFilter', name: '审批状态', type: 'select', options: reviewStateOption },
        { keyword: 'costWrite', name: '成本填写', type: 'select', options: costWriteOption, disabled: activeName !== '待审批' },
        { keyword: 'costConfirm', name: '成本确认', type: 'select', options: costConfirmOption, disabled: activeName !== '待核算' },
        { keyword: 'departmentId',
          name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList
        },
        { keyword: 'cooperationDepartment', name: '协作部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        {
          keyword: 'operateMode', name: '运营模式', valueName: 'value', labelName: 'label', multiple: true, collapseTags: true,
          childrenVal: 'children', type: 'cascaderSelect', checkStrictly: false, options: this.operateModeList
        }, // v2.9.2
        { keyword: 'isMyPending', name: '待我处理', type: 'select', options: [
          { value: true, label: '是' }
        ] },
        { keyword: 'relatedInvoice', name: '发票关联状态', type: 'select', options: [{ value: 0, label: '待关联' }, { value: 1, label: '已关联' }] },
        { keyword: 'hasScreenshots', name: '是否有截图', type: 'select', options: [
          { value: true, label: '是' }, { value: false, label: '否' }
        ] },
        { keyword: 'hasData', name: '是否有数据', type: 'select', options: [
          { value: true, label: '是' }, { value: false, label: '否' }
        ] },
        { keyword: 'tag', name: '标签', valueName: 'name', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        { keyword: 'isPicked', name: '是否开启采集', type: 'select', options: [
          { value: 1, label: '是' }, { value: 0, label: '否' }
        ] },
        { keyword: 'isQueryOrder', name: '是否关联询单', type: 'select', options: [
          { value: 1, label: '是' }, { value: 0, label: '否' }
        ] },
        // settleStatus  0：待结算，1：已结算，2：结算中
        { keyword: 'orderTime', labelWidth: '96px', name: '下单日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'arrivalTime', labelWidth: '96px', name: '到账日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', labelWidth: '96px', name: '创建时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'orderSealMonth', labelWidth: '96px', name: '订单封账月份', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'deleteTime', labelWidth: '96px', name: '删除时间', timeType: 'daterange', type: 'rangeDate', disabled: !this.isDustbin },
        { keyword: 'costTime', labelWidth: '96px', name: '成本创建时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'resourceAttributionMatrixId', name: '所属经营体', labelWidth: '96px', type: 'conditionSelect', selectType: 'cascaderSelectWithChild', excludeKey: 'resourceAttributionMatrixIdEqual', childrenVal: 'children', options: this.deptTreeList }
      ];
      return arr;
    },
    tabListData() {
      if (this.orderMode === 1) {
        return [];
      }
      return this.tabList;
    },
    displayData() {
      return [
        { data: this.orderStatistics.totalPrice, label: '总含税金额', icon: incomeAmountIcon },
        { data: this.orderStatistics.totalTaxCost, label: '总成本', icon: costIcon },
        { data: this.orderStatistics.maori, label: '毛利', icon: rmb },
        { data: this.orderStatistics.profit, label: '毛利率', unit: '%', icon: maoriIcon }
      ];
    },
    modeList() {
      return [
        { mode: 0, name: '变更', handleClick: this.changeOrderMode },
        { mode: 1, name: '最终', handleClick: this.changeOrderMode }
      ];
    },
    inEdit() {
      return this.viewOptions.some(el => !!el.edit);
    }
  },
  watch: {
    paramsObj: {
      handler(data) {
        // 默认筛选含有下单平台和下单形式，需要获取下单形式数据, 仅首次执行
        if (!this.list.isInit) return;
        if (data && data.orderPlatformId) {
          this.$nextTick(() => this.getOrderForm());
        }
      },
      immediate: true,
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editOrder' || from.name === 'orderDetail' || from.name === 'orderupload') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.clearMixinSelection();
      this.fetchData(false);
    } else {
      this.initParams();
      const { accountState, executor, queryOrderSn } = this.$route.query;
      if (accountState !== undefined) {
        this.isShowFilter = true;
        this.paramsObj.accountState = [Number(accountState)];
      } else {
        this.isShowFilter = false;
      }
      executor && this.$set(this.paramsObj, 'orderOperator', executor);
      queryOrderSn && this.$set(this.paramsObj, 'queryOrderSn', queryOrderSn);
      this.activeId = this.$route.query.process !== undefined ? Number(this.$route.query.process) : this.activeId;
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    }
    // keep-alive首次 代替created 让列表数据优先请求
    if (this.list.isInit) {
      this.getSettingData();
      // 筛选条件相关
      this.getOperate();
      this.incomeTypeList();
      this.costItemList();
      this.platformList();
      this.needCategoryList();
      this.queryDeptTreeList();
      this.getOrderForm();
      this.queryTagTreeList();
      this.getViewList();
    }
  },
  methods: {
    hasRouteAuth,
    relatedQueryOrder() {
      if (!this.selectOrderList.length) {
        this.$message.warning('请选择要关联询单的订单');
        return;
      }
      this.showRelatedQueryOrder = true;
    },
    confirmRelatedQueryOrder(data) {
      this.showRelatedQueryOrder = false;
      const ids = this.selectOrderList.map(it => it.id).join(',');
      const params = {
        ids,
        id: data.id
      };
      queryOrderRelated(params).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
          if (this.$refs.showRelatedQueryOrder) this.$refs.showRelatedQueryOrder.init();
        }
      }).catch(error => console.error(error));
    },
    initParams() {
      this.paramsObj = {};
      // 清空选中
      this.clearMixinSelection();
      this.activeId = '';
      this.orderStatus = 0;
      // 处理通过钉钉通知进来的页面
      if (this.$route.query.orderStatus) {
        this.activeId = Number(this.$route.query.orderStatus);
      }
      // 从智能结算跳到订单列表需要筛选的参数
      const jumpOrderParams = strJsonParse(localStorage.getItem('jumpOrderParams'));
      if (jumpOrderParams) {
        localStorage.removeItem('jumpOrderParams');
        Object.keys(jumpOrderParams).forEach(key => {
          this.$set(this.paramsObj, key, jumpOrderParams[key]);
        });
      }
      // 提交封账后未处理订单跳转过来的筛选条件添加
      const sealBillType = Number(this.$route.query.sealBillType);
      const dateStart = Number(this.$route.query.dateStart);
      const dateEnd = Number(this.$route.query.dateEnd);
      if (sealBillType && dateStart && dateEnd || sealBillType === 0 && dateStart && dateEnd) {
        this.paramsObj = {
          sealBillType
        };
        const arrTime = [dateStart * 1000, dateEnd * 1000];
        this.paramsObj.orderTime = arrTime;
        if (this.$refs.FilterToolRef && this.$refs.FilterToolRef.level === 'normal') this.$refs.FilterToolRef.changeLevel();
      }
    },
    /**
     * 获取数据
     */
    // 获取统计数据
    async getOrderData() {
      try {
        const params = this.getParams();
        delete params.ids;
        const res = await getOrderStatistics(params);
        if (res.code === 200) {
          this.orderStatistics = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取收入类型的列表
    async incomeTypeList() {
      try {
        const result = await getIncomeType();
        if (result.data) {
          result.data.forEach(i => {
            i.value = i.id;
            i.label = i.name;
          });
          this.incomeOptions = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 获取成本项列表
    async costItemList() {
      try {
        const params = { page: 1, perPage: 100, costBelong: 0 };
        const result = await costList(params);
        if (result.data) {
          result.data.items.forEach(i => {
            i.value = i.costId;
            i.label = i.costName;
          });
          this.costItemOptions = result.data.items;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 下单平台
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取下单形式
    async getOrderForm() {
      const params = { orderPlatformId: this.paramsObj.orderPlatformId };
      paramsAryToStr(['orderPlatformId'], params);
      if (!params.orderPlatformId) {
        return;
      }
      try {
        const result = await orderFormList(params.orderPlatformId);
        if (result.data && result.data.length) {
          result.data.forEach(i => {
            i.label = i.value;
            i.value = i.id;
          });
        }
        this.orderFormOption = result.data;
        if (this.paramsObj.orderFormId) {
          const formId = this.orderFormOption.find(i => i.value === this.paramsObj.orderFormId);
          if (!formId) this.$set(this.paramsObj, 'orderFormId', '');
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取运营模式的列表
    getOperate() {
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    // 获取品牌标签
    needCategoryList() {
      getNeedCategoryList().then(res => {
        this.needCategoryAry = res.data;
      }).catch(err => {
        console.error(err);
      });
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      params.process = this.activeId; // 设置tab
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (params.accountBelong && typeof params.accountBelong !== 'string' && params.accountBelong.length > 0) {
        params.accountBelong = params.accountBelong.join(',');
      }
      if (params.needCategoryId) {
        const needCategoryIds = this.searchingLoop(params.needCategoryId, this.needCategoryAry);
        needCategoryIds.push(params.needCategoryId);
        params.needCategoryId = needCategoryIds.join(',');
      }
      params.orderMode = this.orderMode;
      params.page = this.page;
      params.perPage = this.list.perPage;
      return params;
    },
    // 获取列表数据
    fetchData(reset = false, noLoading = false) {
      if (reset) this.page = 1;
      const params = this.getParams();
      delete params.ids;
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.cancelToken = source;
      if (!noLoading) this.listLoading = true;
      getList(this.page, this.list.perPage, params, source.token).then(({ data }) => {
        data.items.map(item => { // 添加订单类型的icon,颜色
          const typeImg = this.orderTypeImg.find(currentValue => item.orderType === currentValue.type);
          if (item.orderInfo.orderKind && item.orderInfo.orderKind.length) item.orderInfo.orderKindName = item.orderInfo.orderKind.map(i => i.orderKindName).join('，');
          item = Object.assign(item, typeImg);
          return item;
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
      }).catch(e => {
        if (!e || e.message !== 'cancel') {
          this.listLoading = false;
        }
        console.log(e);
      });
      if (!this.isDustbin) this.getOrderData();
      this.getTabList();
    },
    // 获取自定义列数据
    getSettingData(showLoading = false) {
      if (showLoading) this.listLoading = true;
      getOrderSetting().then(res => {
        if (showLoading) this.listLoading = false;
        if (res.code === 200 && res.data !== '' && res.data.order) {
          this.orderListSetting = this.jsonParse(res.data.order);
          // 单独给所属经营体增加字段
          for (let i = 0; i < this.orderListSetting.length; i++) {
            if (this.orderListSetting[i].fieldName === 'resourceAttributionMatrix') {
              this.orderListSetting[i].tip = 'entityTip';
              break;
            }
          }
          // 更新数据，上线后旧数据可能没有新增加的自定义列数据，通过匹配新增
          const orderListSettingField = this.orderListSetting.map(i => i.fieldName);
          const initOrderListCopy = JSON.parse(JSON.stringify(initOrderList)).filter(i => {
            return !orderListSettingField.includes(i.fieldName);
          });
          if (initOrderListCopy.length) {
            this.orderListSetting = this.orderListSetting.concat(initOrderListCopy);
          }
          // 更新数据 end
          this.authControl('add');
        } else {
          this.orderListSetting = JSON.parse(JSON.stringify(initOrderList));
          this.authControl();
        }
        this.defaultListSetting = JSON.parse(JSON.stringify(this.orderListSetting));
        if (showLoading) this.fetchData();
      }).catch(err => {
        console.log(err);
      });
    },
    async getTabList() {
      try {
        const params = this.getParams();
        delete params.ids;
        delete params.process;
        const result = await getOrderListTab(params);
        if (result.code === 200) {
          result.data.unshift({ name: '全部', id: '' });
          result.data.push({ name: '回收站', id: -2, isLast: true, img: true });
          this.tabList = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 操作
     */
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    handleTabClick(id) {
      const accountStateTabId = this.findTabsId('待核销');
      const sealBillTypeTabId = this.findTabsId('待封账');
      this.activeId = id;
      this.paramsObj.process = this.activeId;
      this.paramsObj.costWrite = '';
      this.paramsObj.costConfirm = '';
      if (accountStateTabId && this.activeId === accountStateTabId) { // 切换待核销tab时，把核销类型筛选清空
        this.paramsObj.accountState = '';
      }
      if (sealBillTypeTabId && this.activeId === sealBillTypeTabId) { // 切换待封账tab时，把核销类型筛选清空
        this.paramsObj.sealBillType = '';
      }
      this.sortName = '';
      this.sortType = '';
      this.$set(this.paramsObj, 'deleteTime', '');
      this.fetchData(true);
    },
    handelFilterInputChange({ value, item }) {
      if (item.keyword === 'orderPlatformId') {
        this.$set(this.paramsObj, 'orderFormId', '');
        const hasVal = Array.isArray(value) && value.length;
        hasVal ? this.getOrderForm() : (this.orderFormOption = []);
      }
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.$set(this.paramsObj, 'exactForClientName', 0);
      this.$set(this.paramsObj, 'exactForActualClientName', 0);
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.list.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleSelectionChange(e) {
      this.selectOrderList = e;
      this.paramsObj.ids = e.map(item => {
        return item.id;
      }).join(',');
    },
    clearMixinSelection() {
      if (this.$refs.orderTableContainer && this.$refs.orderTableContainer.clearMixinSelection) {
        this.$refs.orderTableContainer.clearMixinSelection();
      }
    },
    changeOrderMode(val) {
      this.orderMode = val;
      this.activeId = '';
      this.paramsObj.orderType = '';
      this.fetchData(true);
    },
    updateList() {
      this.fetchData();
    },
    handelSubmit(val) {
      if (val !== -1) {
        // 不是默认则需更新当前视图数据
        this.getViewList(val);
      } else {
        this.getSettingData(true);
      }
      this.$refs.orderTableContainer.tableKey++;
    },
    btnDel(scope) {
      let msg = '是否确定删除该订单';
      if (scope.row.orderType === 5) { // 调整单
        msg = '请确定删除该调整单及其关联的对冲单';
      } else if (scope.row.orderType === 8) { // 变更单
        msg = '请确定删除该变更单及其关联的对冲单';
      }
      showModal(msg).then(_ => {
        delOrder(scope.row.id).then(res => {
          this.$message.success('删除成功');
          if (this.list.items && this.list.items.length > 1) {
            this.fetchData();
          } else if (this.list.items.length === 1) {
            this.fetchData(true);
          }
          this.clearMixinSelection();
        });
      });
    },
    tobatchDelOrder() {
      if (!this.paramsObj.ids || this.paramsObj.ids === '') {
        ElMessage.warning('请选择要删除的订单');
        return;
      }
      const reject = this.selectOrderList.some(i => {
        return i.orderStatus >= 4;
      });
      if (reject) {
        ElMessage.warning('所选择的订单包含：待封账、封账中、已封账、已完成订单无法删除，请去掉后再执行批量删除操作');
        return;
      }
      showModal('是否确定删除订单').then(_ => {
        const params = { ids: this.paramsObj.ids };
        batchDelOrder(params).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchData(true);
            this.clearMixinSelection();
            document.body.scrollTop = document.documentElement.scrollTop = 0;
          }
        }).catch(err => {
          console.error(err);
        });
      });
    },
    tobatchUpdate() {
      if (!this.paramsObj.ids || this.paramsObj.ids === '') {
        ElMessage.warning('请选择要更新的订单');
        return;
      }
      this.$refs.updateInfoDialog.dialogVisibleShow(this.paramsObj.ids);
    },
    uploadDialogShow() {
      this.$refs['uploadDialogRef'].dialogShow();
    },
    exportBeforeExport() {
      const params = this.getParams();
      params.exportType = 0;
      if (this.$refs.moreOpeatorRef) {
        let msg = '<div>是否确定导出数据？</div>';
        if (!params.ids) {
          msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
        }
        this.$refs.moreOpeatorRef.btnExport(params, 'exportRef', msg);
      }
    },
    toCreate() {
      this.$router.push({ name: 'batchcreate' });
    },
    batchPublish(data = null) {
      let ids = '';
      let defaultUser = [];
      if (!data || data.ids === '') {
        if (this.selectOrderList.length === 0) {
          ElMessage.warning('请选择要提交的订单');
          return;
        }
        const orderIds = this.selectOrderList.map(item => item.id);
        const params = {
          id: orderIds.join(),
          isValidate: true,
          isSendMsg: false
        };
        publishOrder(params).then(res => {
          if (res.data && res.data.ids) {
            const examineOrder = this.selectOrderList.filter(item => res.data.ids.includes(item.id));
            ids = examineOrder.map(item => {
              if (item.clientInfo && item.clientInfo.marketId) {
                defaultUser.push({ id: item.clientInfo.marketId, userName: item.clientInfo.market });
              }
              return item.id;
            }).join(',');
            // 有未采集到的订单
            if (res.data.ids.length !== orderIds.length) {
              showModal('所提交订单中存在</br>未采集或未上传截图的订单', '', {
                center: true,
                showClose: true,
                confirmButtonText: '仅发布有截图订单',
                cancelButtonText: '取消发布',
                customClass: 'public-btn del-message del-message-cancel'
              }).then(() => {
                this.$refs.examineRef.batchPublish(ids, defaultUser);
              });
            } else {
              // 所有订单都采集到数据
              this.$refs.examineRef.batchPublish(ids, defaultUser);
            }
          }
        });
      } else {
        ids = data.ids;
        defaultUser = data.defaultUser || [];
        this.$refs.examineRef.batchPublish(ids, defaultUser);
      }
    },
    batchExamine(data = null) {
      let ids = '';
      let defaultUser = [];
      if (!data || data.ids === '') {
        if (this.selectOrderList.length === 0) {
          ElMessage.warning('请选择要审批的订单');
          return;
        }
        const examineOrder = this.selectOrderList;
        if (examineOrder.length === 0) {
          ElMessage.warning('所选择的订单中，都无审批权限');
          return;
        }
        ids = examineOrder.map(item => {
          if (item.clientInfo && item.clientInfo.marketId) defaultUser.push({ id: item.clientInfo.marketId, userName: item.clientInfo.market });
          return item.id;
        }).join(',');
      } else {
        ids = data.ids;
        defaultUser = data.defaultUser || [];
      }
      if (this.$refs.examineRef) this.$refs.examineRef.batchExamine(ids, defaultUser);
    },
    batchBack(data = null) {
      let defaultMsg;
      let summary;
      let isSeal;
      // v2.8.8 取消待核算步骤（2）
      // else if (this.activeId === 2) {
      //   summary = '请确认是否将订单撤回上一步';
      //   defaultMsg = '您有被退回待发布的订单';
      //   isSeal = false;
      // }
      if (this.activeId === 1) {
        summary = '请确认是否将订单撤回到草稿中';
        defaultMsg = '您的订单信息有误，请及时调整后提交';
        isSeal = false;
      } else if (this.activeId === 3) {
        summary = '请确认是否将订单撤回上一步';
        defaultMsg = '您有被退回待发布的订单';
        isSeal = false;
      } else if (this.activeId === 4) {
        summary = '请确认是否将订单撤回上一步';
        isSeal = true;
      }
      let ids = '';
      let defaultUser = [];
      if (!data || data.ids === '') {
        if (this.selectOrderList.length === 0) {
          ElMessage.warning('请选择要提交的订单');
          return;
        }
        const examineOrder = this.selectOrderList;
        ids = examineOrder.map(item => {
          if (item.orderStatus === 1 && item.clientInfo && item.clientInfo.marketId) {
            defaultUser.push({ id: item.clientInfo.marketId, userName: item.clientInfo.market });
          } else {
            if (item.orderInfo.orderOperator) defaultUser.push(...item.orderInfo.orderOperator);
          }
          return item.id;
        }).join(',');
      } else {
        ids = data.ids;
        defaultUser = data.defaultUser || [];
      }
      if (this.$refs.examineRef) this.$refs.examineRef.batchBack(ids, defaultUser, defaultMsg, summary, this.activeId, isSeal);
    },
    openSetting() {
      this.$refs.orderSetting.openDialog(this.orderListSetting, this.curView);
    },
    // 打开报表导出时间选择弹窗
    openDateDialog() {
      this.dateDialog = true;
      const params = _.cloneDeep(this.paramsObj);
      params.orderMode = this.orderMode;
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      this.$refs.exportFinance.initParams(params);
    },
    // 按变更模板导出
    exportTemplateExport() {
      const params = this.getParams();
      params.exportType = 2;
      let msg = '<div>是否确定导出数据？</div>';
      if (!params.ids) {
        msg = msg + `<div style="color: red;font-size: 14px;">单次最多导出5000条</div>`;
      }
      if (this.$refs['moreOpeatorRef']) {
        this.$refs['moreOpeatorRef'].btnExport(params, 'templateExportRef', msg);
      }
    },
    batchPick() {
      if (this.selectOrderList.length === 0) {
        ElMessage.warning('请选择需要开启采集的渠道订单');
        return;
      }
      const canSelectRes = this.selectOrderList.every(item => {
        return ['微信', '微博', '小红书'].includes(item.orderPlatform);
      });
      if (!canSelectRes) {
        ElMessage.warning('仅微信、微博、小红书平台订单可开启采集');
        return;
      }
      showModal('请确认开启采集？').then(_ => {
        const ids = this.selectOrderList.map(item => item.id).join();
        batchPick({ ids }).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功!');
            this.clearMixinSelection();
            this.fetchData();
          }
        }).catch(_ => {});
      });
    },
    /* tobatchCreateInvoice() {
      if (!this.paramsObj.ids || this.paramsObj.ids === '') {
        ElMessage.warning('请选择订单');
        return;
      }
      const params = {
        ids: JSON.stringify(JSON.parse(JSON.stringify(this.paramsObj.ids)).split(','))
      };
      this.$router.push({
        name: 'createInvoice',
        query: params
      });
    }, */
    createOrder() {
      this.$router.push({ name: 'createOrder' });
    },
    setExamineLoading(data) {
      this.examineLoading = data;
    },
    closeDateDialog() {
      this.dateDialog = false;
    },
    /**
     * 工具
     */
    /* 递归循环品牌标签获取id START */
    searchingLoop(needCategoryId, ary) {
      const itemAry = this.getItemAry(ary, needCategoryId);
      return this.setId(itemAry);
    },
    setId(ary) {
      const needCategoryIds = [];
      const loop = (list) => {
        for (const i in list) {
          needCategoryIds.push(list[i].id);
          if (list[i].item && list[i].item.length) {
            loop(list[i].item);
          }
        }
      };
      loop(ary);
      return needCategoryIds;
    },
    getItemAry(list, needCategoryId) {
      let ans = null;
      const callback = (listItem, id) => {
        for (let i = 0; i < listItem.length; i++) {
          if (listItem[i].id === id) {
            ans = listItem[i].item;
            return listItem[i].item;
          }
          if (listItem[i].item) {
            callback(listItem[i].item, id);
          }
        }
      };
      callback(list, needCategoryId);
      return ans;
    },
    /* 递归循环品牌标签获取id END */
    findTabsId(name) {
      const item = this.tabList.find(i => i.name === name);
      return item ? item.id : '';
    },
    authControl(type) {
      /**
        - 客户信息查看/编辑：勾选状态下，可 查看/编辑 订单用户信息(含列表、详情)
        - 发布信息编辑：勾选状态下，可 编辑 下单链接/上传文件信息：
        - 成本信息编辑：勾选状态下，可 编辑 除微任务成本/ID外的成本信息
        - 其他信息编辑：勾选状态下，可 编辑 除客户、发布、成本外的信息
      */
      /**
       * type的作用：
       * 为了解决媒介权限的用户突然增加全向展示的权限，会导致自定义列中没有 客户信息相关的列
       * add: 如果不是媒介用户，判断接口返回的标题列表是否拥有 客户信息，如果没有，需要添加上
       */
      if (!this.isClientInfo) {
        // 如果没有客户信息权限，移除客户信息 i.fieldName !== 'mastermind' i.fieldName !== 'market' &&
        this.orderListSetting = this.orderListSetting.filter(i => {
          return !['clientId', 'clientName', 'actualClientName', 'contactPerson', 'customerOrderNum'].includes(i.fieldName);
          // return i.fieldName !== 'clientName' &&
          // i.fieldName !== 'contactPerson';
        });
      } else if (
        type === 'add' &&
        !this.isClientInfo &&
        this.orderListSetting &&
        this.orderListSetting !== '' &&
        this.orderListSetting.length > 0
      ) {
        // 如果不是媒介用户和内品用户，判断接口返回的标题列表是否拥有 客户信息，如果没有，需要添加上
        const tempArr = this.orderListSetting.map(i => i.fieldName);
        if (!tempArr.includes('clientName')) {
          this.orderListSetting.push({ name: '客户名称', isShow: false, fieldName: 'clientName' });
        }
        if (!tempArr.includes('market')) {
          this.orderListSetting.push({ name: '销售', isShow: false, fieldName: 'market' });
        }
        if (!tempArr.includes('contactPerson')) {
          this.orderListSetting.push({ name: '联系人', isShow: false, fieldName: 'contactPerson' });
        }
        if (!tempArr.includes('mastermind')) {
          this.orderListSetting.push({ name: '策划执行人', isShow: false, parentField: 'clientInfo', fieldName: 'mastermind' });
        }
      }
    },
    jsonParse(str) {
      if (typeof str !== 'string') return str;
      try {
        return JSON.parse(str);
      } catch (error) {
        console.log(error);
        return JSON.parse(JSON.stringify(initOrderList));
      }
    },
    getViewList(val) {
      // 请求视图列表数据
      getOrderView().then((res) => {
        if (res.code === 200) {
          res.data.map(item => {
            item.edit = false;
            return item;
          });
          this.viewOptions = res.data;
          this.viewOptions.unshift({ id: -1, name: '默认视图', edit: false });
          if (val && val === this.curView) {
            console.log(val);
            this.changeView(val);
          }
        }
      }).catch(() => {
      });
    },
    getCurView() {
      // 获取当前视图名称
      const temp = this.viewOptions.filter(item => item.id === this.curView);
      return temp[0].name;
    },
    changeView(item) {
      if (this.editView && item.id !== this.editMode.id) {
        ElMessage.warning('请先取消编辑视图后再切换');
        return;
      }
      // 切换视图选项，为number时是弹窗关闭时切换，否则为点击切换
      if (typeof item === 'number') {
        if (item === -1) {
          this.orderListSetting = this.defaultListSetting;
        } else {
          this.curView = item;
          const temp = this.viewOptions.filter(err => err.id === item);
          if (temp[0] && temp[0].data) {
            this.orderListSetting = this.jsonParse(temp[0].data);
          }
        }
      } else {
        this.curView = item.id;
        this.curViewName = item.name;
        if (item.id === -1) {
          // 默认
          this.orderListSetting = this.defaultListSetting;
        } else {
          const temp = this.viewOptions.filter(err => err.id === item.id);
          if (temp[0] && temp[0].data) {
            this.orderListSetting = this.jsonParse(temp[0].data);
          }
        }
      }
      this.popoverVisible = false;
      this.authControl();
    },
    handleEditView(item) {
      this.cancelEdit();
      // 打开编辑视图
      item.edit = true;
      this.editView = true;
      this.curViewName = item.name;
      this.editMode = {
        id: item.id,
        name: item.name
      };
    },
    handleSaveEdit() {
      const currEditItem = this.viewOptions.find(item => item.edit);
      // 保存视图
      const params = {
        id: currEditItem.id,
        name: this.editMode.name,
        data: currEditItem.data
      };
      editOrderView(params).then(res => {
        if (res.code === 200) {
          this.cancelEdit();
          ElMessage.success('操作成功');
          this.getViewList();
        }
      });
    },
    cancelEdit() {
      this.viewOptions.forEach(item => {
        item.edit = false;
      });
      this.editView = false;
      this.editMode = {
        id: -1,
        name: ''
      };
      // this.curViewName = '';
    },
    handleDelView(val) {
      showModal('是否删除该视图？').then(_ => {
        delOrderView(val).then(res => {
          if (res.code === 200) {
            if (val === this.curView) {
              this.curView = -1;
              this.getViewList(-1);
            } else {
              this.getViewList();
            }
            ElMessage.success('操作成功');
          }
        });
      });
    }
  }
};
</script>
<style lang="scss">
.public-btn .el-button--default:first-child {
  margin-right: -236px !important;
}
.public-btn {
  .el-message-box__btns {
    padding-left: 80px !important;
  }
}
.view-filter-popover {
  border-radius: 8px !important;
  padding: 0 4px 16px !important;
}
</style>
<style  lang="scss" scoped>
.order {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
}
.delete-button-container {
  flex:1;
  height: 32px;
  display: flex;
  align-items: center;
}
.view-box {
  padding: 0 6px 0 0;
  margin: 0;
  list-style: none;
  max-height: 200px;
  @include scrollBar($x: hidden, $y: auto, $width: 6px);
  .view-option {
    min-width: 180px;
    height: 28px;
    list-style: none;
    padding: 4px 0 4px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 0;
    font-size: 14px;
    color: #666;
    cursor: pointer;
    .operate-icon {
      width: 18px;
      height: 18px;
    }
    .mr4 {
      margin-right: 4px;
    }
  }
  .active-view {
    color: #406eff;
    background-color: #edeef2;
    font-weight: 600;
    border-radius: 4px;
  }
  .operate-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 4px;
  }
  .pl0 {
    padding-left: 0;
  }
  &::v-deep {
    .el-input {
      width: 180px;
    }
  }
}
.default-view {
  height: 32px;
  width: 120px;
  margin-right: 12px;
  border-radius: 4px;
  font-size: 14px;
  border: 1px solid #ddd;
  cursor: pointer;
  .view-name {
    width: 80px;
    justify-content: center;
    padding: 0 4px;
    color: #666;
    &:hover {
      color: #406eff;
    }
  }
  .view-icon {
    border-left: 2px solid #ddd;
    height: 16px;
    width: 40px;
    text-align: center;
  }
}
.tag-input {
  display: flex;
  align-items: center;
  // background-color: #fff;
  &::v-deep {
    .el-input__inner {
      // background-color: #fff;
      font-size: 14px;
      // padding: 0 !important;
      // border: none;
      // height: 100%;
      // margin-right: 20px !important;
    }
    .el-input__icon {
      cursor: pointer;
      // margin-right: -12px;
    }
    .el-icon-check {
      color: #406eff;
    }
    .el-input__suffix {
      display: flex;
      align-items: center;
      font-size: 14px;
    }
    .el-icon-error {
      width: 14px !important;
      height: 14px !important;
      position: absolute;
      top: -8px;
      right: -10px;
    }
  }
}
</style>
